package cn.sczc.jh.client.controller.historydata;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import cn.sczc.jh.client.base.AbstractController;
import cn.sczc.jh.client.entity.SensorHistory;
import cn.sczc.jh.client.service.sensorHistory.SensorHistoryService;
import cn.sczc.jh.client.vo.ChartVo;

@RestController
@RequestMapping("/historyData")
public class HistoryDataController extends AbstractController {
	@Autowired
	private SensorHistoryService sensorHistoryService;

	/**
	 * 查询历史数据最后时间
	 */
	@RequestMapping(value = "queryHistoryGasDataDate", method = RequestMethod.POST)
	public ResponseEntity<?> queryHistoryGasDataDate() {
		List<String> dateList = sensorHistoryService.getLastDate();
		return ResponseEntity.ok(dateList);
	}

	/**
	 * 查询历史气体数据
	 */
	@RequestMapping(value = "queryHistoryGasData", method = RequestMethod.POST)
	public ResponseEntity<?> queryHistoryGasData(@RequestBody Map<String, Object> params) {
		Map<String, Object> pageParams = new HashMap<>();
		pageParams.put("pageNum", params.get("pageNum"));
		pageParams.put("pageSize", params.get("pageSize"));
		if (params.get("deviceSerial") != null && !"".equals(params.get("deviceSerial").toString())) {
			String code = params.get("deviceSerial").toString();
			params.put("deviceSerial", Integer.valueOf(code).intValue());
		}
		@SuppressWarnings("unchecked")
		Page<SensorHistory> page = (Page<SensorHistory>) super.getPage(pageParams);
		Page<SensorHistory> data = sensorHistoryService.queryHistoryGasData(page, params);
		return ResponseEntity.ok(data);
	}

	/**
	 * 查询历史气体图表
	 */
	@RequestMapping("queryHistoryGasChart")
	public ResponseEntity<?> queryHistoryGasChart(@RequestBody Map<String, Object> params) {
		ChartVo data = sensorHistoryService.queryHistoryGasChart(params);
		return ResponseEntity.ok(data);
	}

	/**
	 * 气体数据导出
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "downLoadGasDataEXL")
	public String downLoadGasDataEXL(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 取出带查询条件的所有数据allList
		String p = request.getParameter("param").toString();
		String param = new String(p.getBytes("ISO8859-1"), "UTF-8");
		@SuppressWarnings("unchecked")
		Map<String, Object> params = JSON.parseObject(param, HashMap.class);
		if (params.get("deviceSerial") != null && !"".equals(params.get("deviceSerial").toString())) {
			String code = params.get("deviceSerial").toString();
			params.put("deviceSerial", Integer.valueOf(code).intValue());
		}
		List<SensorHistory> allList = sensorHistoryService.queryHistoryGasDataNoPage(params);
		if (allList != null && allList.size() > 0) {
			// 通过工具类创建writer，默认创建xls格式
			BigExcelWriter writer = (BigExcelWriter) ExcelUtil.getBigWriter();
			writer.addHeaderAlias("timeString", "时间");
			writer.addHeaderAlias("sensorAddress", "设备编号");
			writer.addHeaderAlias("batteryVoltage", "电量");
			writer.addHeaderAlias("gasName", "气体名称");
			writer.addHeaderAlias("gasConcentration", "浓度值");
			writer.addHeaderAlias("measurementUnit", "单位");
			writer.addHeaderAlias("desc", "报警描述");
			writer.setOnlyAlias(true);
			// 一次性写出内容，使用默认样式，强制输出标题
			writer.write(allList, true);
			// out为OutputStream，需要写出到的目标流

			// response为HttpServletResponse对象
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			//中文编码
	        String fileName = new String("历史气体数据".getBytes("GB2312"), "ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename="+fileName+".xlsx");
			ServletOutputStream out = response.getOutputStream();

			writer.flush(out, true);
			// 关闭writer，释放内存
			writer.close();
			// 此处记得关闭输出Servlet流
			IoUtil.close(out);
		}
//		if (allList != null && allList.size() > 0) {
//			// 循环sheet
//			DownloadExcelUtil dExlUtile = null;
//			int dataNum = 1;
//			for (SensorHistory item : allList) {
//				// 设置对象：title，value ，List<entity>
//				StringBuffer sb = new StringBuffer();
//				sb.append("时间_");
//				sb.append(item.getTimeString() != null ? item.getTimeString() : "-");
//				sb.append("$");
//				sb.append("设备编号_");
//				sb.append(item.getSensorAddress() != null ? item.getSensorAddress() : "-");
//				sb.append("$");
//				sb.append("气体名称_");
//				sb.append(item.getGasName() != null ? item.getGasName() : "-");
//				sb.append("$");
//				sb.append("浓度值_");
//				String rdz = item.getBatteryVoltage() + item.getMeasurementUnit();
//				sb.append(!"".equals(rdz) ? rdz : "-");
//				sb.append("$");
//				sb.append("报警描述_");
//				sb.append(item.getDesc() != null ? item.getDesc() : "-");
//				String tvsb = sb.toString();
//				// tvsb = tvsb.substring(0, tvsb.length() - 1);
//				String[] tvsbArray = tvsb.split("\\$");
//				List<ExlVo> entityList = new ArrayList<ExlVo>();
//				if (tvsbArray.length > 0) {
//					for (String tv : tvsbArray) {
//						ExlVo entity = new ExlVo();
//						String[] tvArray = tv.split("_");
//						entity.setTitle(tvArray[0]);
//						entity.setValue(tvArray.length == 1 ? "-" : tvArray[1]);
//						entityList.add(entity);
//					}
//				}
//				if (dataNum == 1) {// 若为第一次循环
//					// 在response中写入exl。传入当前type的name，和文件名：DownloadExcelUtil
//					dExlUtile = new DownloadExcelUtil(response, "历史气体数据", "历史气体数据");
//					// 把list<entity>中的title按list的顺序放入String【】，调用：setExcelListTitle
//					String[] titleArray = new String[entityList.size()];
//					for (int i = 0; i < entityList.size(); i++) {
//						titleArray[i] = entityList.get(i).getTitle();
//					}
//					dExlUtile.addRow(titleArray, BorderLineStyle.THIN, jxl.format.Alignment.CENTRE, "bold");
//					// dExlUtile.setExcelListTitle(titleArray);
//					// 把list<entity>中的value按list的顺序放入String【】，调用：addRow
//					String[] valueArray = new String[entityList.size()];
//					for (int i = 0; i < entityList.size(); i++) {
//						valueArray[i] = entityList.get(i).getValue();
//					}
//					dExlUtile.addRow(valueArray, BorderLineStyle.THIN, jxl.format.Alignment.CENTRE, "");
//				} else {
//					// 把list<entity>中的value按list的顺序放入String【】，调用：addRow
//					String[] valueArray = new String[entityList.size()];
//					for (int i = 0; i < entityList.size(); i++) {
//						valueArray[i] = entityList.get(i).getValue();
//					}
//					dExlUtile.addRow(valueArray, BorderLineStyle.THIN, jxl.format.Alignment.CENTRE, "");
//				}
//				dataNum++;
//			}
//			dExlUtile.reportExcel();
//
//		} else {
//			// 查询结果为空
//		}
		return null;
	}

}
